/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.user.controller;

import io.renren.common.dto.MsgTextDTO;
import io.renren.common.redis.RedisUtils;
import io.renren.common.utils.Result;
import io.renren.common.utils.SMSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Map;

/**
 * 接收短信，存储短信 提供短信查询
 */
@RestController
@RequestMapping("/api/msg")
@Api(tags="短信接口")
public class ApiMsgTextController{

    @Autowired
    public RedisUtils redisUtils;

    private static final String KEY="msg:";

    //@Login
    @GetMapping
    @ApiOperation(value="获取短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型", paramType = "query", required = true, dataType="string") ,
            @ApiImplicitParam(name = "phone", value = "手机号码", paramType = "query",required = true, dataType="string") ,
    })
    public Result<MsgTextDTO> get(@ApiIgnore @RequestParam Map<String, Object> params){
        Result<MsgTextDTO> result = new Result<>();
        String type = (String)params.get("type");
        String phone = (String)params.get("phone");
        String key =KEY+type+phone;
        MsgTextDTO msgText1 = (MsgTextDTO)this.redisUtils.get(key,10);
        result.setData(msgText1);
        return result;
    }

    //@Login
    @PostMapping
    @ApiOperation("接收并存储短信")
    public Result<Object> save(@RequestBody MsgTextDTO dto){
        MsgTextDTO msgTextDTO = SMSUtils.smsBuild(dto.getContent()).getSMSObject();
        msgTextDTO.setPhone(dto.getPhone());
        msgTextDTO.setType(dto.getType());
        /**
         * 同一手机号，同一类型的短信验证码只存储最新的，并且有效时间为100秒
         */
        String key =KEY+msgTextDTO.getType()+msgTextDTO.getPhone();
        this.redisUtils.delete(key);
        this.redisUtils.set(key,msgTextDTO,150);
        return new Result<>();
    }

    /**
     * 可以准确找到确定位数的验证码
     * @param args
     */
    /*public static void main(String[] args) {
        String msg= "尾号1234的账号，登陆验证码为123452，请妥善保管，请勿交给他人";
        String msg1= "平安银行登陆验证码：123452，请妥善保管，请勿交给他人";
        MsgTextDTO dto = SMSUtils.smsBuild(msg).getSMSObject();
        System.out.println(dto.getCode4());
        dto = SMSUtils.smsBuild(msg1).getSMSObject();
        System.out.println(dto.getCode6());
    }*/
}